package com.project.template.controller;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.template.common.PageVO;
import com.project.template.common.Result;
import com.project.template.entity.Sign;
import com.project.template.entity.SignRecord;
import com.project.template.service.SignRecordService;
import com.project.template.service.SignService;
import com.project.template.vo.SignVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


/**
 * <p>
 * 通知 前端控制器
 * </p>
 *
 * @author lhp
 *
 */
@RestController
@RequestMapping("/sign")
public class SignController {
    @Resource
    SignService signService;
    @Resource
    SignRecordService signRecordService;
    /**
     * 列表
     * @return
     */
    @ApiOperation(value = "用户列表", notes = "")
    @GetMapping("/list")
    public Result<List<Sign>> list() {
        return new Result<>().success(signService.list());
    }

    /**
     * 分页查询
     * @param name
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public Result<PageVO<Sign>> findPage(@RequestParam(defaultValue = "") String name,
                                           @RequestParam(defaultValue = "1") Integer pageNum,
                                           @RequestParam(defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<Sign> wrapper = new LambdaQueryWrapper<>();
        //查出的数据根据id降序排列
        wrapper.orderByDesc(Sign::getId);
        Page<Sign> page = signService.page(new Page<>(pageNum,pageSize),wrapper);
        return new Result<>().success(new PageVO<>(page));
    }

    /**
     * 数据新增
     * @param sign
     * @return
     */
    @ApiOperation(value = "数据新增", notes = "数据新增")
    @PostMapping("/add")
    public Result add(@Validated @RequestBody Sign sign) {
//        sign.setUser(Utils.getUser().getUsername());
//        sign.setCreateTime(new Date());
        signService.save(sign);
        return new Result<>().success();
    }

    /**
     * 数据更新
     * @param sign
     * @return
     */
    @ApiOperation(value = "数据更新", notes = "数据更新")
    @PutMapping("/update")
    public Result updateById(@Validated @RequestBody Sign sign) {
        signService.updateById(sign);
        return new Result<>().success();
    }

    /**
     * 根据id删除
     * @param ids
     * @return
     */
    @ApiOperation(value = "数据根据id批量删除", notes = "数据根据id批量删除")
    @DeleteMapping("/delBatch")
    public Result delBatch(@RequestBody List<Integer> ids) {
        signService.removeByIds(ids);
        return new Result<>().success();
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/getById")
    public Result<Sign> getById(@RequestParam("id") Integer id) {
        Sign sign = signService.getById(id);
        return new Result<>().success(sign);
    }

    @PostMapping("doSign")
    public Result saveFace(@RequestBody SignVO signRequest) {
        String base64Data = signRequest.getBase64Data();
        int number = signRequest.getNumber();
        String username = signRequest.getUsername();
        String clazzId = signRequest.getClazzId();
        String signNumber = signRequest.getSignNumber();
        String image_base64= base64Data.substring(22);
        SignRecord signRecord = new SignRecord();
        signRecord.setSignTime(DateUtil.now());
        byte[] decodedBytes = Base64.getDecoder().decode(image_base64);
        signRecord.setSignPic(decodedBytes);
        signRecord.setNumber(number);
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedTime = currentTime.format(formatter);
        signRecord.setSignTime(formattedTime);
        signRecord.setClazzId(clazzId);
        signRecord.setSignNumber(signNumber);
        signRecord.setUsername(username);
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:5000/check";
        int getNumber = number;
        // 设置请求体
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 构建 JSON 请求体
        String requestBody = "{"
                + "\"image\": \"" + image_base64 + "\","
                + "\"number\": " + getNumber
                + "}";
        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);
        // 发送 POST 请求
        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
        String jsonResponse = response.getBody();
        JSONObject jsonObject = new JSONObject(jsonResponse);
        String message = jsonObject.toString();
        if(message.contains("200")){
            if (signRecordService.isSign(username,signNumber)) {
                message = "请勿重复签到!";
                return new Result<>().success(message);
            }
            signRecord.setState(1);
            signRecordService.save(signRecord);
            message = "签到成功!";
        }
        else {
            if (signRecordService.isSign(username,signNumber)) {
                message = "请勿重复签到!";
                return new Result<>().success(message);
            }
            signRecordService.save(signRecord);
            message = "签到失败!";
        }
        if(message.equals("签到成功!")) return new Result<>().success(message);
        else return new Result<>().error(message);

    }

    @GetMapping("getByClazzId")
    public Result<PageVO<Sign>> findSignPage(@RequestParam(defaultValue = "") String clazzId,
                                         @RequestParam(defaultValue = "1") Integer pageNum,
                                         @RequestParam(defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<Sign> wrapper = new LambdaQueryWrapper<>();
        //查出的数据根据id降序排列
        if (clazzId != null) {
            wrapper.eq(Sign::getClazzId, clazzId).orderByDesc(Sign::getId);
        }

        Page<Sign> page = signService.page(new Page<>(pageNum,pageSize),wrapper);
        return new Result<>().success(new PageVO<>(page));
    }
}
